package com.system.connect.springboot_flowers.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.system.connect.springboot_flowers.entity.Cartitems;
import com.system.connect.springboot_flowers.dto.CartitemsDto;
import com.system.connect.springboot_flowers.entity.Flowers;
import com.system.connect.springboot_flowers.entity.Payments;
import com.system.connect.springboot_flowers.service.ICartitemsService;
import com.system.connect.springboot_flowers.service.IFlowersService;
import com.system.connect.springboot_flowers.service.IPaymentsService;
import com.system.connect.springboot_flowers.utils.R;
import com.system.connect.springboot_flowers.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 购物车条目表 前端控制器
 * </p>
 *
 * @author yang
 * @since 2025-01-19
 */
@RestController
@RequestMapping("/api/cartitems")
public class CartitemsController {

    @Autowired
    private ICartitemsService cartitemsService;

    @Autowired
    private IFlowersService flowersService;

    @Autowired
    private IPaymentsService paymentsService;

    /**
     * 加入购物车
     */
    @PostMapping("addCart/{flowerId}")
    public R addToCart(@PathVariable Integer flowerId) {

        Cartitems cartitems = new Cartitems();
        cartitems.setFlowersId(flowerId);
        cartitems.setUserId(Integer.valueOf(TokenUtils.getUser()));

        QueryWrapper<Cartitems> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", cartitems.getUserId());
        queryWrapper.eq("flowers_id", cartitems.getFlowersId());
        Cartitems cartitem = cartitemsService.getOne(queryWrapper);
        //查询购物车中是否已经有该商品
        if (cartitemsService.getOne(queryWrapper) != null&& cartitem.getToolId() == null) {
            // 如果购物车中已经有该商品，则数量加1
            System.out.println("cartitems.getQuantity():"+cartitem.getQuantity());
            cartitems.setQuantity(cartitem.getQuantity() + 1);
            // 更新购物车中商品的数量
            cartitemsService.update(cartitems, queryWrapper);
            return R.success("已经存在购物车");
        }
        else if ( cartitem == null){
            cartitems.setQuantity(1);
            cartitemsService.save(cartitems);
        }
        return R.success("加入购物车成功");
    }

    /**
     * 获取购物车列表
     */
    @GetMapping("/getCartList")
    public R getCartList() {

        ArrayList<CartitemsDto> cartitemsList = new ArrayList<>();

        String userIdStr = TokenUtils.getUser();

        if (userIdStr == null || userIdStr.isEmpty()) {
            return R.error("用户信息无效");
        }

        try {
            Integer userId = Integer.valueOf(userIdStr);
            QueryWrapper<Cartitems> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);

            List<Cartitems> cartItemsList = cartitemsService.list(queryWrapper);

            for (Cartitems cartitems : cartItemsList) {
                Flowers flowers = flowersService.getById(cartitems.getFlowersId());
                CartitemsDto cartitemsDto = new CartitemsDto();
                cartitemsDto.setItemId(flowers.getFlowerId());
                cartitemsDto.setName(flowers.getName());
                cartitemsDto.setPrice(flowers.getPrice());
                cartitemsDto.setImage(flowers.getFlowerPhoto());
                cartitemsDto.setQuantity(cartitems.getQuantity());
                cartitemsDto.setTotalPrice(cartitems.getQuantity() * flowers.getPrice());
                cartitemsList.add(cartitemsDto);
            }


            if (cartItemsList.isEmpty()) {
                return R.success("购物车为空");
            }
            return R.success(cartitemsList);
        } catch (NumberFormatException e) {
            return R.error("用户ID格式错误");
        }
    }


    @PostMapping("/batchdelete")
    public R batchDelete(@RequestBody BatchOperationRequest request) {
        // Logic for batch deletion
        List<CartitemsDto> items = request.getItems();
        for (CartitemsDto item : items) {
            cartitemsService.removeById(item.getItemId());
        }
        return R.success("批量删除成功");
    }

    @PostMapping("/batchcheckout")
    public R batchCheckout(@RequestBody BatchOperationRequest request) {
        System.out.println("request.getItems():"+request.getItems());
        // Logic for batch checkout
        List<CartitemsDto> items = request.getItems();

        if (items == null || items.isEmpty()) {
            R.success("0.0");
        }
        Double totalPrice = 0.0;
        for (CartitemsDto item : items) {
            if (item.getItemId() != null) {
                // 如果是鲜花，则根据鲜花ID获取鲜花信息
                Flowers flowers = flowersService.getById(item.getItemId());
                System.out.println("item.getQuantity():"+item.getQuantity());
                System.out.println("flowers.getPrice():"+flowers.getPrice());
                totalPrice += item.getQuantity() * flowers.getPrice();
            }
        }

        /*
        * 1.生成订单
         */
        Payments payments = new Payments();
        payments.setUserId(Integer.valueOf(TokenUtils.getUser()));
        payments.setAmount(totalPrice);
        payments.setStatus("支付成功");
        payments.setTransactionId("1234567890");
        paymentsService.save(payments);

        return R.success(totalPrice);



    }

    // dto for batch operations
    public static class BatchOperationRequest {
        private List<CartitemsDto> items;

        // Getters and setters
        public List<CartitemsDto> getItems() {
            return items;
        }

        public void setItems(List<CartitemsDto> items) {
            this.items = items;
        }
    }
}

